var Addpoint = function(){
	this.menu_name = 'Add Point MN';
}

Addpoint.prototype.Refresh = function(){
	// Clean up old values
	var $category = $('#category');
	$category.empty();
	
	$.each(window.expense, function(i, expense){
		$('<option></option>').appendTo($category).attr('value', expense.name).html(expense.name);
		$('<option></option>').appendTo($('#filter_category')).attr('value', expense.name).html(expense.name);
	});
	$('<option></option>').attr('value', 'Miscellaneous').html('Miscellaneous').appendTo($category);
	
	$datepicker = $('#datepicker').datepicker();
	$datepicker.datepicker('setDate', (new Date()));
	$datepicker.datepicker( "option", "dateFormat", "dd/mm/yy" );
	
	
	$.each(window.purchase, function(i, purchase){
		AddPurchaseToList(purchase);
	});
}

Addpoint.prototype.SubmitPurchase = function(){
	var data = {
		amount: $('input#amount').val(),
		category: $('#category').val(),
		date: $('#datepicker').val()
	};
	console.log(data);
		
	$.post('/save_instance', {type: 'purchase', data: data}, (function(data){
		return function(){
			window.purchase.push(data);
			AddPurchaseToList(data);
			$('#amount').val('');
		}
		})(data),
		'json'
	);
	
}

Addpoint.prototype.ValidateInput = function(){}

Addpoint.prototype.DeletePurchase = function(id){
	for(var key in window.purchase){
		var purchase = window.purchase[key];
		if(purchase._id == id){
			window.purchase.splice(key, 1);
			break;
		}
	}
	
	$('#'+id).remove();
	
	$.post('/delete_instance', {id: id, type: 'purchase'}, function(){});
}

function AddPurchaseToList(item){
	if($('#'+item._id).length == 0){
		var $entry = $('<tr></tr>').attr('id', item._id).appendTo($('table#history'));
		$('<td>'+item.category+'</td>').appendTo($entry);
		$('<td>'+item.amount+'</td>').appendTo($entry);
		$('<td>'+item.date+'</td>').appendTo($entry);
		$('<td><a href="#" onclick="window.addpoint.DeletePurchase(\''+item._id+'\')">Delete</a></td>').appendTo($entry);
	}
}
var frequencies = {
	1: 'Daily',
	7: 'Weekly',
	14: 'Fortnightly',
	30: 'Monthly',
	91: 'Quarterly',
	183: 'Semi-Anually',
	365: 'Anually'
};
